export const addRoutes = (parentName,children,router)=>{
    let hasNewRoute=false
    children.forEach( item => {
        if(item && !router.hasRoute(item.name)){
            hasNewRoute=true
            if(parentName&&parentName.trim()!==''){
                router.addRoute(parentName,item)
            }else{
                router.addRoute(item)
            }
        }
        if(item.children && item.children.length){

            const childHasNewRoute=addRoutes(item.name,item.children,router)

            if(!hasNewRoute){
                hasNewRoute=childHasNewRoute
            }

        }
    })
    return hasNewRoute;
}


export const buildRouteTree=(routeList)=>{

    const routeTree=[]

    routeList.forEach(item=>{

        let route={...item}

        route.component=loadComponent(route.component)

        route.meta=JSON.parse(route.meta)

        if(route.children&&route.children.length>0){
            route.children=buildRouteTree(route.children)
        }

        routeTree.push(route)
    })

    return routeTree
}

export const treeify=(roots,list)=>{
    roots.forEach(root=>{
        const children=list.filter(item=>{
            if(root.id===item.parentId){
                item.parent={...root}
                item.parent.children=[]
                return true
            }

            return false
        })

        root.children=children

        treeify(children,list)
    })
}

function getParentPath(path,list,parentPath){
    if(!list||list.length===0)return null
    const item=list.filter(item=>item.path===path)[0]
    if(item){
        parentPath.push(item)
        return item
    }else{
        for(let item of list){
            const result=getParentPath(path,item.children,parentPath)
            if(result){
                parentPath.push(item)
                return item
            }
        }
    }
}


//从dataList树形结构中找出parentId==data.id的data
export const findParentData=(parentId,dataList)=>{
    let parent=dataList.filter(item=>parentId===item.id)[0]


    if(parent){
        return parent
    }else{
        for(let item of dataList){
            let result=null
            if(item.children){
                result=findParentData(parentId,item.children)
            }
           if(result){
               parent=result
               break
           }
        }
    }
    return parent
}

//使用vite懒加载
let views = import.meta.glob("@/views/**/*.vue");
let layouts=import.meta.glob("@/layout/**/*.vue");


function loadComponent(path){
    if(path.startsWith("views")){
        return viewsComponent(path)
    }else if(path.startsWith('layout')){
        return layoutComponent(path)
    }
}
function viewsComponent(path) {
    return views[`/src/${path}`]
}

function layoutComponent(path){
    return layouts[`/src/${path}`]
}